package cc.shacocloud.kotlin.tools.cli

/**
 * 隔离类加载器
 *
 * 使用 [AntPathMatcher] 匹配路径
 *
 * @author 思追(shaco)
 * @see AntPathMatcher
 */
class IsolationClassLoader(

    /**
     * 类加载器
     */
    classLoader: ClassLoader,

    /**
     * 白名单配置，前缀匹配
     */
    whitelist: Set<String> = emptySet(),

    /**
     * 黑名单配置，前缀匹配
     */
    blacklist: Set<String> = emptySet()

) : ClassLoader(classLoader) {

    private val whitelist: List<String> = ArrayList(whitelist)

    private val blacklist: List<String> = ArrayList(blacklist)


    override fun loadClass(name: String, resolve: Boolean): Class<*> {
        val className = name.replace('/', '.')

        // 黑名单匹配
        for (item in blacklist) {
            if (className.startsWith(item)) {
                throw ClassNotFoundException(className)
            }
        }

        // 白名单匹配
        for (item in whitelist) {
            if (className.startsWith(item)) {
                return super.loadClass(name, resolve)
            }
        }
        throw ClassNotFoundException(className)
    }
}
